package com.ybc.chinese.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.ybc.chinese.R;
import com.ybc.chinese.adapter.TeacherVideoAdapter;
import com.ybc.chinese.bean.TeacherVideo;
import com.ybc.chinese.utils.CacheUtil;
import com.ybc.chinese.utils.CommonUtil;
import com.ybc.chinese.utils.Contants;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

/**
 * <p>网上教学视频<p/>
 * Created by Yubch on 17/2/19.
 */
public class TeacherVideoActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener2<ListView> {

    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.iv_left)
    ImageView ivLeft;
    @Bind(R.id.lv_outside_read)
    PullToRefreshListView lvOutSideRead;

    private Context mCtx;
    private static final String INDEX_TEACHER_VIDEO = "index/teacher/video";
    private int mOffset = 0;
    private TeacherVideoAdapter mAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_outside_read);
        mCtx = this;
        ButterKnife.bind(this);
        initView();
        List<TeacherVideo> teacherVideos = getCache();
        if(!CommonUtil.isEmpty(teacherVideos)) {
            mAdapter.setData(teacherVideos, false);
        } else {
            showRunningDialog();
        }
        request();
    }

    private void initView() {
        tvTitle.setText(getString(R.string.online_teach_video));
        ivLeft.setImageResource(R.mipmap.ic_back);
        ivLeft.setVisibility(View.VISIBLE);
        mAdapter = new TeacherVideoAdapter(mCtx);
        lvOutSideRead.setAdapter(mAdapter);
        lvOutSideRead.setMode(PullToRefreshBase.Mode.BOTH);
        lvOutSideRead.setOnRefreshListener(this);
    }

    private List<TeacherVideo> getCache() {
        String jsonTeacherVideo = CacheUtil.getCache(mCtx, INDEX_TEACHER_VIDEO);
        List<TeacherVideo> teacherVideos = new ArrayList<>();
        if(!TextUtils.isEmpty(jsonTeacherVideo)) {
            teacherVideos = new Gson().fromJson(jsonTeacherVideo, new TypeToken<List<TeacherVideo>>(){}.getType());
        }
        return teacherVideos;
    }

    @Override
    protected void onDestroy() {
        ButterKnife.unbind(this);
        super.onDestroy();
    }

    @OnClick(R.id.iv_left)
    public void back() {
        finish();
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        mOffset = 0;
        request();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        request();
    }

    private void request() {
        if (!CommonUtil.isNetworkConnected(mCtx)) {
            dismissRunningDialog();
            CommonUtil.showToast(mCtx, R.string.no_net);
            lvOutSideRead.onRefreshComplete();
            return;
        }
        BmobQuery<TeacherVideo> query = new BmobQuery<>();
        query.setLimit(Contants.LIMIT);
        query.setSkip(mOffset);
        //按照时间降序
        query.order("-createdAt");
        //执行查询，第一个参数为上下文，第二个参数为查找的回调
        query.findObjects(new FindListener<TeacherVideo>() {

            @Override
            public void done(List<TeacherVideo> list, BmobException e) {
                if (e == null) {
                    try {
                        if(mOffset == 0) {
                            mAdapter.setData(list, false);
                            CacheUtil.saveCache(mCtx, INDEX_TEACHER_VIDEO, new Gson().toJson(list));
                        } else {
                            mAdapter.setData(list, true);
                        }
                        mOffset = mOffset + list.size();
                    } catch (Exception ignore) {
                    }
                } else {
                    CommonUtil.showToast(mCtx, "数据请求失败");
                }
                dismissRunningDialog();
                lvOutSideRead.onRefreshComplete();
            }
        });
    }
}
